package email_server

import (
	"bytes"
	_ "embed"
	"fmt"
	"github.com/chicken-team-outside/chicken_transmission/proxy_server/setting"
	"html/template"
	"io"
	"mime"
	"net/smtp"
)

//go:embed email_template/email.html
var emailTemplate string

var emailTemplateEngine *template.Template

var emailAuth smtp.Auth

var emailServerAddr string

func Init() error {
	emailAuth = smtp.PlainAuth("", setting.SmtpUser, setting.SmtpPassword, setting.SmtpHost)
	emailServerAddr = fmt.Sprintf("%s:%d", setting.SmtpHost, setting.SmtpPort)
	var err error
	emailTemplateEngine, err = template.New("email").Parse(emailTemplate)
	if err != nil {
		return fmt.Errorf("failed to convert email template: %w", err)
	}
	return nil
}

func createContent(subject, to string, content func(writer io.Writer) error) ([]byte, error) {
	msg := bytes.NewBuffer(nil)
	var err error
	_, err = msg.WriteString(fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\nMIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n\r\n", mime.QEncoding.Encode("UTF-8", setting.ServerName), mime.QEncoding.Encode("UTF-8", to), mime.QEncoding.Encode("UTF-8", subject)))
	if err != nil {
		return nil, err
	}
	if err = content(msg); err != nil {
		return nil, err
	}
	return msg.Bytes(), nil
}

func SendVerifyCode(to, functionName, captcha string, maxAge int) error {
	content, err := createContent("验证码", to, func(writer io.Writer) error {
		return emailTemplateEngine.Execute(writer, map[string]interface{}{
			"captcha":      captcha,
			"cacheMaxAge":  maxAge / 60,
			"functionName": functionName,
		})
	})
	if err != nil {
		return err
	}
	return smtp.SendMail(emailServerAddr, emailAuth, setting.SmtpUser, []string{to}, content)
}
